<template>
  <div v-loading="listLoading" class="goodsDetail-container app-container">
    <div class="detail-title">商品信息</div>
    <div class="detail-content">
      <el-form ref="detailForm" label-width="80px" :model="detailQuery" :rules="detailRules">
        <el-row>
          <el-col :span="6">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="detailQuery.goods_name" maxlength="32" placeholder="请输入商品名称" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="货物类别">
              <el-select v-model="detailQuery.type_4_kinds" placeholder="货物类别" clearable class="filter-item select-item">
                <el-option v-for="item in typeKinds" :key="item.enum_key" :label="item.enum_value1" :value="item.enum_key" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="一级分类" prop="id_public_goods_type">
              <el-select value-key="id_public_goods_type" v-model="detailQuery.type_name" placeholder="一级分类" clearable class="filter-item select-item" @change="selectTypeFather" @clear="clearTypeFather">
                <el-option v-for="item in typeFather" :key="item.id_public_goods_type" :label="item.type_name" :value="item" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="二级分类" prop="type_child">
              <el-select value-key="id_public_goods_type" v-model="detailQuery.child_name" :disabled="childDisable" placeholder="二级分类" clearable class="filter-item select-item" @change="handleSelectChild">
                <el-option v-for="item in typeChild" :key="item.id_public_goods_type" :label="item.type_name" :value="item" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="6">
            <el-form-item label="产地" prop="goods_region">
              <el-input v-model="detailQuery.goods_region" maxlength="10" placeholder="请输入产地" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="存储方式">
              <el-select v-model="detailQuery.goods_storetype" placeholder="存储方式" clearable class="filter-item select-item">
                <el-option v-for="item in storetype" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="零售规格" prop="sales_describe">
              <el-input v-model="detailQuery.sales_describe" maxlength="12" placeholder="请输入零售规格" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="商品毛重">
              <el-input v-model="detailQuery.gross_weight" type="number" maxlength="3" placeholder="请输入商品毛重" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="6">
            <el-form-item label="单位数量">
              <el-input v-model="detailQuery.minimal_weight" maxlength="3" placeholder="请输入单位数量" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="营销标签">
              <el-select v-model="detailQuery.type_promotion" placeholder="营销标签" clearable class="filter-item select-item">
                <el-option v-for="item in promotion" :key="item.enum_key" :label="item.enum_value1" :value="item.enum_key" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="品牌名称" prop="brand_name">
              <el-input v-model="detailQuery.brand_name" maxlength="10" placeholder="请输入品牌名称" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="商品标签">
              <el-input v-model="detailQuery.tag_4_goods" maxlength="10" placeholder="请输入商品标签" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="商品型号">
              <el-input v-model="detailQuery.goods_selections" type="textarea" maxlength="300" show-word-limit placeholder="输入商品颜色/尺寸等属性，各属性之间以分号隔开，分隔符不能用'-'; 例如：36码/红色;37码/蓝色;38码/绿色" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="商品描述" prop="goods_dec">
              <el-input v-model="detailQuery.goods_dec" type="textarea" maxlength="300" show-word-limit placeholder="请输入商品描述" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col>
            <el-form-item label="商品主图">
              <UploadMainImages ref="goodsMainImage" :limit="1" @imageList="getMainImage" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col>
            <el-form-item label="详情图片">
              <UploadImages ref="goodsDecPic" :key-word="'goodsDescImage'" :limit="20" @imagesData="getImageData" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col>
            <el-form-item label="补充图片">
              <UploadImages ref="goodsImageList" :key-word="'goodsImageList'" :limit="20" @imagesData="getImageData" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <div class="submit-button">
        <el-button v-if="pageStatus === 'create'" type="primary" @click="handleCreate">提交</el-button>
        <el-button v-else type="primary" @click="handleUpdate">保存</el-button>
      </div>
    </div>
  </div>
</template>

<script>
import waves from '@/directive/waves'
import { goodsList, goodsKinds, goodsListOld } from '@/api/goods' // waves directive
import { scrollTo } from '@/utils/scroll-to'
import UploadMainImages from '@/components/UploadImages/UploadMainImages'
import UploadImages from '@/components/UploadImages/UploadImages'
import { dataFilter } from 'echarts/lib/component/marker/markerHelper'

export default {
  name: 'GoodsDetail',
  components: { UploadMainImages, UploadImages },
  directives: { waves },
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'info',
        deleted: 'danger'
      }
      return statusMap[status]
    }
  },
  data() {
    return {
      listLoading: true,
      /* 步骤条 */
      stepActive: 0,
      /* 页面类型 */
      pageStatus: '',
      /* 商品分类 */
      childDisable: true,
      typeFather: [],
      typeChild: [],
      /* 商品类别 */
      typeKinds: [],
      /* 营销标签 */
      promotion: [],
      /* 存储方式 */
      storetype: [
        { value: '0', label: '冷冻' },
        { value: '1', label: '冷藏' },
        { value: '2', label: '常温' }
      ],
      /* 商品补充图 */
      goods_image_list: [],
      /* 详情信息 */
      detailQuery: {
        id_public_goods_info: null,
        type_child: null,
        child_name: null,
        id_public_goods_type: null,
        type_name: null,
        type_4_kinds: 1,
        goods_storetype: '0',
        goods_name: null,
        goods_region: null,
        sales_describe: null,
        gross_weight: null,
        minimal_weight: null,
        type_promotion: 0,
        brand_name: null,
        tag_4_goods: null,
        goods_selections: null,
        goods_dec: null,
        goods_main_image: null,
        goods_dec_pic: null
      },
      detailRules: {
        goods_name: [
          { required: true, message: '请输入商品名称', trigger: 'blur' }
        ],
        id_public_goods_type: [
          { required: true, message: '请选择一级分类', trigger: 'change' }
        ],
        type_child: [
          { required: true, message: '请选择二级分类', trigger: 'change' }
        ],
        goods_region: [
          { required: true, message: '请输入产地信息', trigger: 'blur' }
        ],
        sales_describe: [
          { required: true, message: '请输入零售规格', trigger: 'blur' }
        ],
        brand_name: [
          { required: true, message: '请输入品牌名称', trigger: 'blur' }
        ],
        goods_dec: [
          { required: true, message: '请输入商品描述', trigger: 'blur' }
        ]
      }
    }
  },
  mounted() {
    this.pageStatus = this.$route.params.type
    console.log(this.$route.params)
    if (this.$route.params.type === 'update') {
      this.getGoodsDetails(this.$route.params.id)
    } else {
      this.listLoading = false
    }
    this.getTypeKinds()
    this.getPromotion()
    this.getTypeFather(1)
  },
  methods: {
    /*
    * 获取商品详情
    * */
    getGoodsDetails(id) {
      goodsList(this.Qs.stringify({
        filter_type: 1,
        id_public_goods_info: id,
        invoke_method: 'public_page_4m_load_goods_list',
        pre_db_para_begin_idx: 0,
        pre_db_para_length_4_list: 10
      })).then(response => {
        this.detailQuery = response.page_content[0]

        if (this.detailQuery.goods_main_image.indexOf('http') === -1) {
          this.$refs.goodsMainImage.bannerList = [{
            image_url: 'http://upload-image.jinglintu.cn' + this.detailQuery.goods_main_image
          }]
        } else {
          this.$refs.goodsMainImage.bannerList = [{
            image_url: this.detailQuery.goods_main_image
          }]
        }

        if (this.detailQuery.goods_dec_pic) {
          // eslint-disable-next-line prefer-const
          let imageArray = this.detailQuery.goods_dec_pic.split(',')
          const imageData = []
          imageArray.forEach(item => {
            imageData.push({ image_url: item })
          })
          this.$refs.goodsDecPic.goodsDescImage = imageData
        }

        this.getTypeChild(this.detailQuery.id_public_goods_type)

        this.getGoodsImage()

        setTimeout(() => {
          this.listLoading = false
        }, 0.5 * 1000)
      })
    },
    /*
    * 获取商品补充图片
    * */
    getGoodsImage() {
      goodsListOld(this.Qs.stringify({
        invoke_method: 'public_page_4m_images_4_one_goods',
        id_public_goods_info: this.$route.params.id,
        image_type: 2
      })).then(response => {
        console.log(response)
        this.$refs.goodsImageList.goodsImageList = response.page_content
        this.goods_image_list = response.page_content
      })
    },
    /*
    * 获取货物类别
    * */
    getTypeKinds() {
      goodsKinds(this.Qs.stringify({
        invoke_method: 'public_page_4m_load_enum',
        enum_key: 'type_kinds'
      })).then(response => {
        this.typeKinds = response.page_content
        this.typeKinds.forEach(item => {
          item.enum_key = Number(item.enum_key)
        })
      })
    },
    /*
    * 获取营销标签
    * */
    getPromotion() {
      goodsKinds(this.Qs.stringify({
        invoke_method: 'public_page_4m_load_enum',
        enum_key: 'type_promotion'
      })).then(response => {
        this.promotion = response.page_content
        this.promotion.unshift({ enum_key: 0, enum_value1: '不促销' })
        this.promotion.forEach(item => {
          item.enum_key = Number(item.enum_key)
        })
      })
    },
    /*
    * 获取一级分类数据
    * */
    getTypeFather(filter) {
      goodsList(this.Qs.stringify({
        invoke_method: 'public_page_4m_load_main_cls',
        is_online: 0,
        filter_type: filter,
        pre_cmd_para_show_admin_type: 'super_and_login',
        pre_db_para_begin_idx: 0,
        pre_db_para_length_4_list: 100
      })).then(response => {
        this.typeFather = response.page_content
      })
    },
    selectTypeFather(val) {
      console.log(val)
      this.getTypeChild(val.id_public_goods_type)
      this.detailQuery.id_public_goods_type = val.id_public_goods_type
      this.detailQuery.type_name = val.type_name
      this.childDisable = false
    },
    clearTypeFather() {
      this.childDisable = true
      this.listQuery.id_public_goods_type = null
      this.listQuery.type_child = null
      this.getList()
    },
    /*
    * 获取二级分类数据
    * */
    getTypeChild(id) {
      goodsList(this.Qs.stringify({
        invoke_method: 'public_page_4m_load_child_cls',
        is_online: 0,
        type_father: id,
        pre_db_para_begin_idx: 0,
        pre_db_para_length_4_list: 100
      })).then(response => {
        this.typeChild = response.page_content
      })
    },

    handleSelectChild(val) {
      console.log(val)
      this.detailQuery.type_child = val.id_public_goods_type
      this.detailQuery.child_name = val.type_name
    },

    /*
    * 获取商品主图
    * */
    getMainImage(data) {
      console.log(data)
      this.detailQuery.goods_main_image = data[0].image_url
    },
    /*
    * 获取图片数据
    * */
    getImageData(data, type) {
      if (type === 'goodsImageList') {
        console.log(this.detailQuery)
        console.log(data)
        if (this.$route.query.type === 'update') {
          data.forEach(item => {
            if (item.id_public_goods_image) {
              this.updateGoodsImage(item)
            } else {
              item.id_public_goods_info = this.detailQuery.id_public_goods_info
              this.updateGoodsImage(item)
            }
          });
        } else {
          this.goods_image_list = data
        }
      } else {
        const dataArray = []
        data.forEach(item => {
          dataArray.push(item.image_url)
        })
        this.detailQuery.goods_dec_pic = dataArray.join(',')
      }
    },

    updateGoodsImage(dataParams) {
      goodsList(this.Qs.stringify({
        invoke_method: 'public_page_4m_upd_or_insert_goods_images',
        id_public_goods_info: dataParams.id_public_goods_info,
        image_url: dataParams.image_url,
        is_online: dataParams.is_online,
        pre_db_para_id_public_goods_image: dataParams.id_public_goods_image
      })).then(response => {
        this.$refs.goodsImageList.goodsImageList = []
        this.getGoodsImage()
      })
    },

    /*
    * 提交页面数据
    * */
    handleCreate() {
      this.$refs.detailForm.validate(valid => {
        if (valid) {
          this.listLoading = true
          this.handleUpdate()
        } else {
          scrollTo(0, 800)
          return false
        }
      })
    },

    /*
    * 更新商品数据
    * */
    handleUpdate() {
      goodsList(this.Qs.stringify({
        invoke_method: 'public_page_4m_upd_or_insert_goods_info',
        type_child: this.detailQuery.type_child,
        child_name: this.detailQuery.child_name,
        id_public_goods_type: this.detailQuery.id_public_goods_type,
        type_name: this.detailQuery.type_name,
        type_4_kinds: this.detailQuery.type_4_kinds,
        goods_storetype: this.detailQuery.goods_storetype,
        goods_name: this.detailQuery.goods_name,
        goods_region: this.detailQuery.goods_region,
        sales_describe: this.detailQuery.sales_describe,
        gross_weight: this.detailQuery.gross_weight,
        minimal_weight: this.detailQuery.minimal_weight,
        type_promotion: this.detailQuery.type_promotion,
        brand_name: this.detailQuery.brand_name,
        tag_4_goods: this.detailQuery.tag_4_goods,
        goods_selections: this.detailQuery.goods_selections,
        goods_dec: this.detailQuery.goods_dec,
        goods_main_image: this.detailQuery.goods_main_image,
        goods_dec_pic: this.detailQuery.goods_dec_pic,
        data_weight: this.$route.query.defaultWeight,
        pre_db_para_id_public_goods_info: this.detailQuery.id_public_goods_info
      })).then(response => {
        console.log(response)
        if (this.pageStatus === 'create') {
          console.log(this.goods_image_list.length)
          if (this.goods_image_list.length) {
            this.goods_image_list.forEach(item => {
              item.id_public_goods_info = response.page_content.id_public_goods_info
              this.updateGoodsImage(item)
            });
          }
          this.$notify({
            title: 'Success',
            message: '新增成功',
            type: 'success',
            duration: 2000
          })
          this.$router.push({name: 'GoodsList'})
        } else {
          this.$notify({
            title: 'Success',
            message: '保存成功',
            type: 'success',
            duration: 2000
          })
          this.getGoodsImage()
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
@import "../../styles/variables";
.detail-title {
  padding: 6px 0 12px;
  border-bottom: 2px solid $mainColor;
  font-size: 16px;
}
.detail-content {
  padding: 16px 64px 0;
  .el-row {
    margin-top: 16px;
    .el-input {
      width: 160px;
    }
    .el-textarea {
      width: 87%;
    }
  }
  .submit-button {
    text-align: center;
    .el-button {
      width: 120px;
      height: 40px;
    }
  }

  ::v-deep {
    .el-form-item__label {
      font-weight: normal;
    }
    .el-textarea__inner {
      resize: none;
      height: 90px;
    }
    .el-input__inner{
      line-height: 1px !important;
    }
  }
}
</style>
<style>
  input[type="number"]::-webkit-inner-spin-button, input[type="number"]::-webkit-outer-spin-button {
    -webkit-appearance: none;
    margin: 0;
  }
</style>
